package com.zenithsun.news.specialnews.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.syzg.common.config.SysProperties;
import com.syzg.common.controller.BaseController;
import com.syzg.common.model.WebInfo;
import com.syzg.common.util.SearchMap;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.PKCreator;
import com.syzg.common.exception.BaseException;
import com.syzg.core.page.PageResult;
import com.syzg.core.util.StringUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.security.csrf.CSRFTokenManager;
import com.zenithsun.common.security.sql.SqlInjectionManager;
import com.zenithsun.news.newscolumns.model.NewsColumns;
import com.zenithsun.news.newsinfo.model.Newsinfo;
import com.zenithsun.news.newsinfo.service.NewsinfoService;
import com.zenithsun.news.specialnews.model.Specialnews;
import com.zenithsun.news.specialnews.service.SpecialnewsService;

@Controller
@RequestMapping("/path/specialnews")
public class SpecialnewsController extends BaseController{
	
	static Logger log = LoggerFactory.getLogger(SpecialnewsController.class);
	
	@Resource
	private SpecialnewsService specialnewsService;
	
	@Resource
	private NewsinfoService newsinfoService;
	
	@RequestMapping("/listSpecialnews")
	public ModelAndView listSpecialnews(WebObj webObj)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/listSpecialnews.jsp");
		SearchMap searchMap = SearchMap.forClass(Specialnews.class);
		PageResult pageResult = specialnewsService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
        webObj.setPageResult(pageResult);
        mv.addObject("webObj",webObj);
        return mv;
	}

	@RequestMapping(value = "/listSpecialnewsToJson", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String listSpecialnewsToJson(int pageNo,int limit,Specialnews sn,HttpServletRequest request)throws Exception{
		if(StringUtil.isNotBlank(sn.getTitle())){CSRFTokenManager.validateForm(request);}
		
		OutMessage outMessage = new OutMessage();
//		SearchMap searchMap = SearchMap.forClass(Specialnews.class);
		PageResult pageResult = specialnewsService.findObjectsByList(pageNo, limit, sn);
		outMessage.setContent(pageResult);
		outMessage.setState(OutMessageState.Success);
		String result= JSON.toJSONString(outMessage);
		return result;
	}
	
	@RequestMapping("/initSpecialnews")
	public ModelAndView initSpecialnews() throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/addSpecialnews.jsp");
		try {
			mv.addObject("specialnews", new Specialnews());
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.specialnews.setCreatePersonId(new String(loginObj.getPersonId()));
			this.specialnews.setCreator(loginObj.getPersonName());
			this.specialnews.setCreateTime(new Date());*/
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/addSpecialnews")
	public @ResponseBody String addSpecialnews(Specialnews specialnews,String selectedNews) throws Exception {
		WebObj webObj = new WebObj();
		try {
			specialnews.setId(PKCreator.getPk());
			specialnews.setCreateTime(new java.sql.Timestamp(new Date().getTime()));
			specialnewsService.createSpecialNews(specialnews, selectedNews);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/viewSpecialnews")
	public ModelAndView viewSpecialnews(Specialnews specialnews,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/news/specialnews/viewSpecialnews.jsp");
		try {
			String id = specialnews.getId();
			Specialnews specialnewsVO = specialnewsService.findObjectById(id);
			mv.addObject("specialnews",specialnewsVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/editSpecialnews")
	public ModelAndView editSpecialnews(String id) throws Exception {
		SqlInjectionManager.validateSqlParam(id);
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/editSpecialnews.jsp");
		try {
			Specialnews specialnews = specialnewsService.findObjectById(id);
			mv.addObject("specialnews", specialnews);
			List<Newsinfo> lstNewsinfo = newsinfoService.getNewsBySNID(id);
			mv.addObject("lstNewsinfo",lstNewsinfo);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/modSpecialnews")
	public @ResponseBody String modSpecialnews(String id,Specialnews specialnewsVO,String selectedNews) throws Exception {
		WebObj webObj = new WebObj();
		try {
			Specialnews specialnews = specialnewsService.findObjectById(id);
			specialnews = (Specialnews) MethodUtil.copyProperties(specialnews, specialnewsVO);
			specialnewsService.updateSpecialNews(specialnews,selectedNews);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/delSpecialnews")
	public ModelAndView delSpecialnews(String id,WebObj webObj,HttpServletRequest request) throws Exception {
		String[] ids = webObj.getSelectedRow();
		try {
			if(ids == null) { //删除单个
				if(id == null) {
					ids = new String[0];
				} else {
					ids = new String[]{String.valueOf(id)};
				}
			}
			String[] idsStr = new String[ids.length];
			int i = 0;
			for(String idVO: ids) {
				idsStr[i++] = new String(idVO);
			}
			specialnewsService.delete(idsStr);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listSpecialnews(webObj);
	}
	
	@RequestMapping("/listNewsinfo")
	public ModelAndView listNewsinfo(WebObj webObj,String newsColId,String title)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/listNewsinfo.jsp");
		Newsinfo newsinfo = new Newsinfo();
		if(StringUtil.isNotEmpty(newsColId)){
			NewsColumns newsColumns = new NewsColumns();
			newsColumns.setId(newsColId);
			newsinfo.setNewsColumns(newsColumns);
		}
		 if(StringUtil.isNotEmpty(title)){
			newsinfo.setTitle(title);
		}
		PageResult pageResult = newsinfoService.queryNewsIsNotSpecial(webObj.getPageNo(), SysProperties.PAGESIZE, newsinfo);
		//PageResult pageResult = specialnewsService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
        webObj.setPageResult(pageResult);
        mv.addObject("webObj",webObj);
        mv.addObject("newsColId",newsColId);
        return mv;
	}
	/**
	 * 选择选择显示的新闻
	 * @param selectedNews
	 * @param snId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/setNews")
	public ModelAndView setNews(String selectedNews,String snId)throws Exception{
		SqlInjectionManager.validateSqlParam(new String[]{selectedNews,snId});
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/listSelectedNewsinfo.jsp");
		if(snId != null && !"".equals(snId))
		{
			List<Newsinfo> list = newsinfoService.getNewsBySNID(snId);
			if(list.size() > 0){
				for (int i = 0; i < list.size(); i++) {
					selectedNews += ","+list.get(i).getId();
				}
			}
		}
		if(StringUtil.isNotEmpty(selectedNews)){
			String[] strAry = selectedNews.split(",");
			List<Newsinfo> lstNewsinfo = newsinfoService.getNewsInIds(strAry,false);
			mv.addObject("lstNewsinfo", lstNewsinfo);
		}
        return mv;
	}
	
	@RequestMapping(value="/getNewsColumns",produces="application/json;charset=UTF-8")
	public @ResponseBody String getNewsColumns()throws Exception{
		
		SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
		@SuppressWarnings("unchecked")
		List<NewsColumns> lstNewsColumns = specialnewsService.findObjects(searchMap);
		List<JSONObject> lstJSONObject = new ArrayList<JSONObject>();
		JSONObject jSONObject = new JSONObject();
		jSONObject.put("id", "0");
		jSONObject.put("pId", "0");
		jSONObject.put("name","所有新闻");
		jSONObject.put("click", "clickNode('0');");
		lstJSONObject.add(jSONObject);
		for(NewsColumns newsColumns : lstNewsColumns){
			jSONObject = new JSONObject();
			jSONObject.put("id", newsColumns.getId());
			jSONObject.put("pId", newsColumns.getParentId());
			jSONObject.put("name",newsColumns.getName());
			jSONObject.put("click", "clickNode('" + newsColumns.getId() + "');");
			lstJSONObject.add(jSONObject);
		}
        return new JSONArray(lstJSONObject).toString();
	}
	
	
	/**
	 * 选择选择显示的新闻
	 * @param selectedNews
	 * @param snId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteSelectNews")
	public ModelAndView deleteSelectNews(String selectedNews,String delId,boolean isSpecial)throws Exception{
		SqlInjectionManager.validateSqlParam(new String[]{selectedNews,delId});
		ModelAndView mv = new ModelAndView("/zenithsun/news/specialnews/listSelectedNewsinfo.jsp");
		if(isSpecial)
		{
			Newsinfo newsInfo = newsinfoService.findNewsinfoById(delId);
			newsInfo.setSnId(null);
			newsinfoService.update(newsInfo);
		}
		if(selectedNews.indexOf(",") < 0)
		{
			selectedNews = "";
		}else{
			selectedNews = selectedNews.replace(","+delId, "");
		}
		if(StringUtil.isNotEmpty(selectedNews)){
			String[] strAry = selectedNews.split(",");
			List<Newsinfo> lstNewsinfo = newsinfoService.getNewsInIds(strAry,false);
			mv.addObject("lstNewsinfo", lstNewsinfo);
		}
        return mv;
	}
}
